import Vue from 'vue'
import Vuex from 'vuex'
import ls from '../utils/localStorage'
import router from '../router'
import axios from '../utils/http'
Vue.use(Vuex)

const state = {
  user: ls.getItem('user'),
  token: ls.getItem('token'),
  auth: ls.getItem('auth')
}

const mutations = {
  UPDATE_USER(state, user) {
    state.user = user
    ls.setItem('user', user)
  },
  SET_TOKEN(state, token) {
    state.token = token
    ls.setItem('token', token)
  },
  UPDATE_AUTH(state, auth) {
    state.auth = auth
    ls.setItem('auth', auth)
  }
}

const actions = {
  login({ commit }, token) {
    if (token) {
      // 换取用户信息
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
      axios.get('user').then( ({data}) => {
        commit('UPDATE_USER', data)
        commit('SET_TOKEN', token)
        commit('UPDATE_AUTH', true)
        router.push('/')
      })
    }
  },
  logout({ commit }) {
    commit('UPDATE_AUTH', false)
    commit('UPDATE_USER', {})
    commit('SET_TOKEN', '')
    router.push({ name: 'Index', params: { logout: true } })
  }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions
})

export default store
